package ygstudio.xue.de.list;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;

import ygstudio.xue.de.db.DB;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class BaseData implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5339910595828373472L;

	private String[] fields;

	private HashMap<String, String> map;

	private String dbTable;

	public String getDbTable() {
		return dbTable;
	}

	public BaseData() {
		map = new HashMap<String, String>();
		fields = new String[] { DB.F_ID, DB.F_TITLE, DB.F_DE, DB.F_CN,
				DB.F_NOTIZ, DB.F_COUNT, DB.F_RATING, DB.F_MEDIA,
				DB.F_MEDIA_START, DB.F_MEDIA_END, DB.F_LAST_TERMIN,
				DB.F_CREATE_DATE, DB.F_NEXT_TERMIN, DB.F_HIDDEN };

		for (String k : fields) {
			map.put(k, "");
		}
	}

	public void setDbTable(String dbTable) {
		this.dbTable = dbTable;
	}

	public long insertToDB(SQLiteDatabase db) {
		ContentValues values = getContentValues();
		values.put(DB.F_CREATE_DATE, new Date().getTime());
		return db.insert(dbTable, null, values);
	}

	private ContentValues getContentValues() {
		ContentValues values = new ContentValues();
		for (String key : fields) {
			if (key.equalsIgnoreCase(DB.F_ID)) {
				continue;
			}
			values.put(key, getValueOf(key));
		}
		return values;
	}

	public long updateDb(SQLiteDatabase db) {
		return db.update(dbTable, getContentValues(), DB.F_ID + "="
				+ getValueOf(DB.F_ID), null);
	}

	public String[] getFields() {
		return fields;
	}

	public String getValueOf(String field) {
		String v = map.get(field);
		if (field.equals(DB.F_COUNT) || field.equalsIgnoreCase(DB.F_RATING) || field.equals(DB.F_CREATE_DATE)) {
			if (v == null || v.trim().isEmpty()) {
				return "0";
			}
		}
		return v;
	}

	public void setValueOf(String field, String value) {
		map.put(field, value);
	}

	public void updateByCursor(Cursor cursor) {
		for (String s : fields) {
			setValueOf(s, cursor.getString(cursor.getColumnIndexOrThrow(s)));
		}
	}
}
